package org.example.security.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.common.utils.DateTimeUtil;
import org.example.db.entity.Permission;
import org.example.db.mapper.PermissionMapper;
import org.example.db.mapper.UserPermissionMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class PermissionService {

    UserPermissionMapper userPermissionMapper;
    PermissionMapper permissionMapper;


    public PermissionService(UserPermissionMapper userPermissionMapper, PermissionMapper permissionMapper) {
        this.userPermissionMapper = userPermissionMapper;
        this.permissionMapper = permissionMapper;
    }

    @Cacheable(value = "permission:userId", key = "#userId")
    public List<Permission> getPermissionListByUserId(Long userId){


        return userPermissionMapper.selectPermissionByUserId(userId);
    }

    @Cacheable(value = "permission:userId", key = "#wxUserId")
    public List<Permission> getPermissionListByWxUserId(Long wxUserId){


        return userPermissionMapper.selectPermissionByWxUserId(wxUserId);
    }



    public List<Permission> getPermissionList() {

        return permissionMapper.selectList(new QueryWrapper<Permission>().last("limit 100"));
    }


    public int setPermission(Permission permission) {
        Assert.notNull(permission.getId(), "数据异常");
        return permissionMapper.updateById(permission);
    }


    public int addPermission(Permission permission) {

        String formatTime = DateTimeUtil.getDateTimeString(LocalDateTime.now());
        permission.setAddTime(formatTime);
        permission.setUpdateTime(formatTime);
        return permissionMapper.insert(permission);
    }


    public int removePermission(Integer permissionId) {
        Assert.notNull(permissionId, "数据异常");
        return permissionMapper.deleteById(permissionId);
    }
}
